package com.mdc.mansion.api.web.common.handler;

import javax.servlet.http.HttpServletResponse;

import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.mdc.mansion.common.response.Result;
import com.mdc.mansion.common.util.JSONUtil;

/**<p>com.mdc.mansion.api.web.common.handler.SystemHandlerMethodReturnValueHandler</p>
 * <p>Title: SystemHandlerMethodReturnValueHandler</p>
 * <p>Copyright: Copyright © 2010-2014</p>
 * <p>Company: jumei</p>
 * @author xiang.liu
 * @version 1.0
 */
public class SystemHandlerMethodReturnValueHandler implements HandlerMethodReturnValueHandler{
   /**
    * (non-Javadoc)
   * @param returnValue
   * @param returnType
   * @param mavContainer
   * @param webRequest
   * @throws Exception
   * @see org.springframework.web.method.support.HandlerMethodReturnValueHandler#handleReturnValue(java.lang.Object, org.springframework.core.MethodParameter, org.springframework.web.method.support.ModelAndViewContainer, org.springframework.web.context.request.NativeWebRequest)
    */
    @Override
    public void handleReturnValue(Object returnValue, MethodParameter returnType,ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {
        if(returnValue == null){
            return;
        }
        HttpServletResponse response = webRequest.getNativeResponse(HttpServletResponse.class);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=UTF-8");
        StringBuffer responseSb = new StringBuffer();
        Result result=(Result)returnValue;
        result.setReqId(webRequest.getParameter("reqId"));
        responseSb.append(JSONUtil.getInstance().writeValueAsString(result));
        response.getWriter().println(responseSb.toString());
        // 表明该请求已经处理，后面spring不会再处理
        mavContainer.setRequestHandled(true);
    }

    
    /**(non-Javadoc)
    * @param returnType
    * @return
    * @see org.springframework.web.method.support.HandlerMethodReturnValueHandler#supportsReturnType(org.springframework.core.MethodParameter)
    */  
    @Override
    public boolean supportsReturnType(MethodParameter returnType) {
        return Result.class.isAssignableFrom(returnType.getParameterType());
    }

}
